package cn.tedu.eguser.controller;

import cn.tedu.eguser.base.response.JsonResult;
import cn.tedu.eguser.base.response.StatusCode;
import cn.tedu.eguser.mapper.UserMapper;
import cn.tedu.eguser.pojo.dto.UserAddParam;
import cn.tedu.eguser.pojo.dto.UserUpdateParam;
import cn.tedu.eguser.pojo.enyity.User;
import cn.tedu.eguser.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Validated
@Slf4j
@Tag(name = "用户管理模块")
@RestController
@RequestMapping("v1/user/")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @Operation(summary = "添加用户")
    @ApiOperationSupport (order= 10)
    @PostMapping("add")
    public JsonResult addUser(@RequestBody @Validated UserAddParam userAddParam) {
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @Operation(summary = "查询用户列表")
    @ApiOperationSupport (order= 20)
    @GetMapping("list")
    public JsonResult listUser() {
        List<UserListVO> listUser = userMapper.listUser();
        return JsonResult.ok(listUser);
    }

    @Operation(summary = "删除用户")
    @ApiOperationSupport (order= 30)
    @PostMapping("del")
    public JsonResult delUser(@Range (min = 1l,max = 100l,message = "用户id范围错误") Long id) {
        int row = userMapper.deleteUser(id);
        if (row > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @Operation(summary = "修改用户")
    @ApiOperationSupport (order= 40)
    @PostMapping("update")
    public JsonResult updateUser(UserUpdateParam userUpdateParam) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        int row = userMapper.updateUserById(user);
        if (row>0) {
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
}
